//
//  AIGirlApplePay.swift
//  AIGirl
//
//  Created by dongyx on 2024/5/20.
//

import UIKit
import StoreKit
import KakaJSON
import MMKV

class AIGirlApplePay: NSObject, UorInXNetworkProtocol {
    
    override init() {
        super.init()
        self.addTransactionObserver()
    }
    
    public static let `default` = AIGirlApplePay()
    
    private var currentBuyProductIdentifier: String?
    
    private var currentProduct: SKProduct?
    
    private var buyUpdateClosure: (() -> Void)?
    
    private var orderId: String = ""
    
    /// 购买商品
    /// - Parameter productId: 商品ID
    /// - Parameter type: 0: 消耗；1：订阅
    func buy(_ productId: String, type: Int, completion: (() -> Void)? = nil) {
        guard !productId.isEmpty else { return }
        MMKV.default()?.set(Int32(type), forKey: productId)
        buyUpdateClosure = completion
        
        ToastTool.show()
        if let _ = AlphaGoCache.orderModel, let transcation = AlphaGoCache.currentTranscation {
            /// 有订单，没有充值成功，直接去后台验证
            verify(transaction: transcation)
        } else {
            currentBuyProductIdentifier = productId
            let request = SKProductsRequest(productIdentifiers: [productId])
            request.delegate = self
            request.start()
        }
    }
    
    /// 订阅
    func subscription(id productId: String, orderId: String, completion: (() -> Void)? = nil) {
        self.orderId = orderId
        buy(productId, type: 1, completion: completion)
    }
    
    /// 检查是否有未完成订单
    func checkIncompleteOrder() {
        if let _ = AlphaGoCache.orderModel, let transcation = AlphaGoCache.currentTranscation {
            /// 有订单，没有充值成功，直接去后台验证
            ToastTool.show()
            verify(transaction: transcation)
        }
    }
    
    private func addTransactionObserver() {
        SKPaymentQueue.default().add(self)
    }
    
    func removeTransactionObserver() {
        SKPaymentQueue.default().remove(self)
    }
    
    // 恢复购买
    func restorePurchases(completion: (() -> Void)? = nil) {
        ToastTool.show()
        buyUpdateClosure = completion
        SKPaymentQueue.default().restoreCompletedTransactions()
    }
    
}


//MARK: - SKProductsRequestDelegate
extension AIGirlApplePay: SKProductsRequestDelegate {
    
    /// 发起购买请求收到回调
    /// - Parameters:
    ///   - request: 请求
    ///   - response: 苹果回复
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        guard response.products.count > 0 else {
            "Product Error！".toast_error
            return }
        /// 请求成功后，拿到苹果返回的购买商品的ID，【一般情况下，只有一条数据，商品只能一个一个购买】，故取first也是可以的
        response.products.forEach {
            if $0.productIdentifier == currentBuyProductIdentifier {
                self.currentProduct = $0
                let payment = SKMutablePayment(product: $0)
                guard SKPaymentQueue.canMakePayments() else { return }
                SKPaymentQueue.default().restoreCompletedTransactions()
                SKPaymentQueue.default().add(payment)
            }
        }
    }
    
    /// 请求完成
    /// - Parameter request: 发出的购买请求
    func requestDidFinish(_ request: SKRequest) {
        debugPrint("[In-App Purchase] - BUY REQUEST COMPLETION，VERIFYING...")
    }
    
    /// 请求失败
    /// - Parameters:
    ///   - request: 发出的购买请求
    ///   - error: 错误信息
    func request(_ request: SKRequest, didFailWithError error: Error) {
        request.cancel()
        debugPrint("[In-App Purchase] - BUY REQUEST，ERROR" + error.localizedDescription + "\n\n")
        ("Buy Faliure!, error: " + error.localizedDescription).toast_error
    }
    
    // 处理恢复的购买
    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
        print("Restore failed: \(error.localizedDescription)")
        ToastTool.dismiss()
    }
    
    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
        print("Restore completed.")
        ToastTool.dismiss()
    }
    
}

//MARK: - SKPaymentTransactionObserver
extension AIGirlApplePay: SKPaymentTransactionObserver {
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case .deferred:
                "Need to wait for confirmation!".toast_error
            case .failed:
                "Buy Faliure!".toast_error
                queue.finishTransaction(transaction)
            case .purchased:
                verifyOldOrder(queue: queue, transaction: transaction)
            case .restored:
                verifyOldOrder(queue: queue, transaction: transaction)
                break
            case .purchasing:
                debugPrint("purchasing...")
            default:
                break
            }
        }
    }
    
    func verifyOldOrder(queue: SKPaymentQueue, transaction: SKPaymentTransaction) {
        guard let transID = transaction.transactionIdentifier else { return }
        if let model = AlphaGoCache.orderModel {
            if model.state == 1 {
                /// 记录当前未充值成功订单
                AlphaGoCache.currentTranscation = transaction
                /// 有订单，没有充值成功，直接去后台验证
                verify(transaction: transaction)
            } else {
                /// 有订单，并且状态是已充值，则直接结束订单
                queue.finishTransaction(transaction)
            }
        } else {
            var model = AlphaGoTransactionModel()
            model.productIdentifier = transaction.payment.productIdentifier
            model.transactionIdentifier = (transID as NSString).longLongValue
            model.orderId = self.orderId
            model.uid = "\(GlobalTool.userModel?.id ?? 0)"
            model.rechargeDate = Date()
            if let date = transaction.transactionDate {
                model.transactionDate = date
            }
            model.state = 1
            AlphaGoCache.save(model)
            verify(transaction: transaction)
        }
    }
    
    /// 根据订单从苹果服务器获取票据
    /// - Parameter transaction: 订单
    func verify(transaction: SKPaymentTransaction) {
        /// 订单支付成功之后，获取票据
        if let receiptUrl = Bundle.main.appStoreReceiptURL {
            do {
                let receiptData = try? Data(contentsOf: receiptUrl)
                guard let base64String = receiptData?.base64EncodedString(options: .endLineWithLineFeed) else {return}
                serveceVerify(base64String, transaction)
            }
        }
    }
    
    /// 服务器验证票据是否充值成功
    /// - Parameters:
    ///   - note: 票据
    ///   - transaction: 订单
    func serveceVerify(_ note: String, _ transaction: SKPaymentTransaction) {
        var model = AlphaGoTransactionModel()
        if let orderModel = AlphaGoCache.orderModel {
            model = orderModel
        } else {
            model.productIdentifier = transaction.payment.productIdentifier
            if let transID = transaction.transactionIdentifier {
                model.transactionIdentifier = (transID as NSString).longLongValue
            }
            model.uid = "\(GlobalTool.userModel?.id ?? 0)"
            model.rechargeDate = Date()
            if let date = transaction.transactionDate {
                model.transactionDate = date
            }
            AlphaGoCache.save(model)
        }
        
        if model.rechargeType == 0 {
            request.start(.VerifyTransaction(baseStr: note)) { result in
                if result.isSuccessful {
                    "Recharged!".toast_success
                    SKPaymentQueue.default().finishTransaction(transaction)
                    self.rechargeSuccessful()
                    
                    GlobalTool.refreshUserInfo()
                }else {
                    result.errorDescripton?.toast_error
                    AlphaGoCache.currentTranscation = transaction
                }
            }
        } else if model.rechargeType == 1 {
            request.start(.subscription(code: model.productIdentifier, orderId: model.orderId, baseStr: note),type: AIGirlVIPModel.self) { result in
                if result.isSuccessful, let model = result.model {
                    SKPaymentQueue.default().finishTransaction(transaction)
                    
                    "Successful".toast_success
                    self.rechargeSuccessful()
                    
                    GlobalTool.refreshUserInfo()
                    UserDefaultsManager.setString(model.createTime.toTimeStr(), forKey: .VIPStartTime)
                    UserDefaultsManager.setString(model.expirationTime.toTimeStr(), forKey: .VIPEndTime)
                    
                    
                    self.buyUpdateClosure?()
                }else {
                    result.errorDescripton?.toast_error
                }
            }
        }
        
    }
    
    private func rechargeSuccessful() {
//        AlphaGoCache.retryRechargeCount = 1
        AlphaGoCache.currentTranscation = nil
        AlphaGoCache.orderModel = nil
        AlphaGoCache.currentOrderString = nil
//        AlphaGoCache.rechargeModel = nil
    }
    
}


//MARK: - 支付模型
struct AlphaGoTransactionModel: Convertible {

    /// 购买用户的标识
    var uid: String = ""
    
    /// 购买状态，只有两种状态：已支付 - 1、已充值 - 2
    var state: Int = 0
    
    /// 充值时间
    var rechargeDate: Date?
    
    /// 下单时间
    var transactionDate: Date?
    
    /// 产品ID
    var productIdentifier: String = ""
    
    /// 订单ID
    var transactionIdentifier: Int64 = 0
    
    /// 充值类型（0：消耗；1：订阅）
    var rechargeType: Int {
        Int(MMKV.default()?.int32(forKey: productIdentifier) ?? 0)
    }
    
    var orderId: String = ""
    
    func alphaGo_identifier() -> String { "transactionIdentifier" }
    
}
